package com.qianfeng.controller;

import com.qianfeng.entity.Result;
import com.qianfeng.entity.User;
import com.qianfeng.service.UserService;
import com.ramostear.captcha.HappyCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Map;
import java.util.Random;

/**
 * 登陆，注册业务的处理器
 * 注意区分请求方式
 * @author 李康
 */
@Controller
public class UserController {

    @Autowired
    UserService service;

    @Autowired
    private MailSender mailSender;

    @RequestMapping("/test")
    @ResponseBody
    public String test(@RequestParam Map<String,String> map) {
        System.out.println("test.map = " + map);
        return "test";
    }

    /**
     * 上传文件保存的路径
     */
    @Value("${config.uploadPath}")
    String uploadPath;

    /**
     * 访问图片的地址(tomcat虚拟目录路径)
     * 例如localhost:8080/images/1.jpg
     */
    @Value("${config.imgSrc}")
    String imgSrc;

    /**
     * 发送验证码的邮箱地址
     */
    @Value("${mail.username}")
    String senderAddr;

    /**
     * 登陆API
     * @param name 用户名
     * @param pwd 密码
     * @param code 验证码
     * @param request requst
     * @return 通用的json实体类
     */
    @RequestMapping(path = "/login",method = RequestMethod.POST)
    @ResponseBody
    public Result login(@RequestParam String name, @RequestParam String pwd, @RequestParam String code, HttpServletRequest request){
        Result result = new Result();
        HttpSession session = request.getSession();
        // 1、检查验证码
        boolean flag = HappyCaptcha.verification(request,code,true);

        if (!flag){
            result.setCode(Result.ERROR);
            result.setMsg("验证码校验失败");
            return result;
        }
        try{
            User user = service.findUser(name);
            // 2、检查密码
            if(user.getPassword().equals(pwd)){
                // 3、写入session，name字段保存用户名,uid保存用户id
                user.setPassword(null);
                request.getSession().setAttribute("USER", user);
//                request.getSession().setAttribute("name",user.getUsername());
//                request.getSession().setAttribute("uid",user.getId());
                result.setCode(Result.SUCCESS);
                return result;
            }else{
                result.setMsg("账号或密码不正确");
                result.setCode(Result.WANING);
                return result;
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(Result.ERROR);
            result.setMsg("登陆异常");
            return result;
        }finally {
            // 4、不论登陆成功与否，立即销毁session中保存的验证码
            HappyCaptcha.remove(request);
        }

    }

    @RequestMapping(path = "/getVailImg",method = RequestMethod.GET)
    public void getCode(HttpServletRequest request, HttpServletResponse response){
        HappyCaptcha.require(request,response).build().finish();
    }

    @RequestMapping(path = "/logout",method = RequestMethod.POST)
    @ResponseBody
    public Result logout(HttpServletRequest request){
        Result result = new Result();
        HttpSession session = request.getSession();
//        session.removeAttribute("name");
//        session.removeAttribute("uid");
        session.removeAttribute("USER");
        result.setCode(Result.SUCCESS);
        return result;
    }

    @RequestMapping(path = "/registered",method = RequestMethod.POST)
    @ResponseBody
    public Result registered(HttpServletRequest request,User user,String code) {
        Result result = new Result();
        HttpSession session = request.getSession();
        // 检查邮箱验证码
        String mailCode = (String) session.getAttribute("mailCode");
        if(mailCode==null || !mailCode.equals(code)){
            result.setCode(Result.ERROR);
            result.setMsg("验证码校验失败");
            return result;
        }
        try {
            // 如果已经用户名重复注册则抛出异常
            service.registered(user);
            result.setCode(Result.SUCCESS);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(Result.ERROR);
            result.setMsg("注册失败");
            return result;
        }finally {
            session.removeAttribute("mailCode");
        }
    }

    @RequestMapping(path = "/upload/image",method = RequestMethod.POST)
    @ResponseBody
    public Result uploadHeadImage(@RequestParam("file") MultipartFile img, HttpServletRequest request){
        Result result = new Result();
        try{
            if(img.getSize()<=0){
                throw new Exception("文件不能为空");
            }
            // 将登陆的用户id作为头像文件名
            Integer uid = (Integer) request.getSession().getAttribute("uid");
            String fileName = img.getOriginalFilename();
            if (fileName == null || fileName.isEmpty()) {
                throw new Exception("上传文件名不能为空");
            }
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
            fileName = uid.toString()+"."+fileType;
            if ("jpg".equals(fileType) || "png".equals(fileType)) {
                File file = new File(uploadPath, fileName);
                img.transferTo(file);
            } else {
                throw new Exception("只允许上传jpg,png格式头像");
            }
            result.setCode(Result.SUCCESS);
            result.setData(imgSrc+fileName);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(Result.ERROR);
            result.setMsg("头像上传异常");
            return result;
        }
    }

    @RequestMapping(value = "/update/user",method = RequestMethod.POST)
    @ResponseBody
    public Result updateUser(User user){
        Result result = new Result();
        try {
            service.updateInfo(user);
            result.setCode(Result.SUCCESS);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(Result.ERROR);
            result.setMsg("更新用户信息失败");
        }
        return result;
    }

    @RequestMapping(value = "/sendVailEmail",method = RequestMethod.POST)
    @ResponseBody
    private Result sendVailMail(HttpServletRequest request,String email){
        Result result = new Result();
        if(email.isEmpty()){
            result.setCode(Result.ERROR);
            result.setMsg("邮箱不能为空");
            return result;
        }
        try{
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom(senderAddr);
            mailMessage.setTo(email);
            mailMessage.setSubject("【疫情大数据可视化】注册验证码");
            String randomCode = randomCode();
            mailMessage.setText("【"+randomCode+"】--- 注册6位验证码");
            mailSender.send(mailMessage);
            request.getSession().setAttribute("mailCode",randomCode);
            result.setCode(Result.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(Result.ERROR);
            result.setMsg("发送验证码失败");
        }
        return result;
    }

    private String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }


}
